package com.metaverse.backend.task;

import com.metaverse.backend.domain.LiveComment;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

/**
 * 多线程下的任务示例是否出现数据不同的情况
 *
 */
public class ExampleTask {

    public static void main(String[] args) {
        ExecutorService executor = Executors.newFixedThreadPool(10);

        // 添加评论任务
        for (int i = 0; i < 10; i++) {
            int finalI = i;
            executor.submit(() -> {
                LiveComment comment = new LiveComment();
                comment.setContent("看电影");
                comment.setNickname("Comment " + finalI);
//                synchronized (Constant.LiveCommentlist) {
//                    Constant.LiveCommentlist.add(comment);
//                }
                Constant.LiveCommentlist.add(comment);
                System.out.println("Added: " + comment.getContent() + " | Current Size: " + Constant.LiveCommentlist.size());
            });
        }

        // 移除评论任务
        for (int i = 0; i < 5; i++) {
            executor.submit(() -> {
                LiveComment comment;
//                synchronized (Constant.LiveCommentlist) {
//                    comment = Constant.LiveCommentlist.poll();
//                }
                comment = Constant.LiveCommentlist.poll();
                if (comment != null) {
                    System.out.println("Removed: " + comment.getContent() + " | Current Size: " + Constant.LiveCommentlist.size());
                } else {
                    System.out.println("Attempted to remove from empty list | Current Size: " + Constant.LiveCommentlist.size());
                }
            });
        }

        executor.shutdown();
        try {
            executor.awaitTermination(1, TimeUnit.MINUTES);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        System.out.println("Final size of LiveCommentlist: " + Constant.LiveCommentlist.size());
    }
}